import collections
import json
import logging
import os

import hvac

from absl import app, flags

FLAGS = flags.FLAGS

KeyInfo = collections.namedtuple(
    'KeyInfo', ['key_path', 'key_content'])

def list_keys(client, path, mount_point, show_secret=False):
  keys = []
  children = client.secrets.kv.list_secrets(path, mount_point)['data']['keys']
  for child in children:
    sub_path = os.path.join(path, child)
    if sub_path.endswith('/'):
      keys.extend(list_keys(client, sub_path, mount_point))
    else:
      key_dict = client.secrets.kv.read_secret_version(
          path=sub_path, mount_point=mount_point)['data']['data']
      assert 'path' not in key_dict
      key_dict['path'] = sub_path
      if not show_secret:
        key_dict = {name: key_dict.get(name) for name in
                    ('generated', 'owner', 'path', 'key_name')}
      keys.append(KeyInfo(sub_path, key_dict))
  return keys


def main(_):
  mount_point = FLAGS.mount_point
  client = hvac.Client(url=FLAGS.vault_addr)
  assert client.is_authenticated()
  keys = []
  key_infos = list_keys(client, FLAGS.path, mount_point)
  for key_info in key_infos:
    print(json.dumps(key_info.key_content, indent=2))


if __name__ == '__main__':
  logging.basicConfig(
      level='DEBUG', format='%(levelname)8s %(asctime)s %(name)s] %(message)s')
  flags.DEFINE_string('vault_addr', None, '')
  flags.DEFINE_string('path', '', '')
  flags.DEFINE_string('mount_point', None, '')

  app.run(main)
